import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gameplay_flutter/lib_runtime/extension/string_extension/string_text.dart';
import 'package:gameplay_flutter/m_room/constants/room_assets.dart';
import 'package:get/get.dart';
import 'package:ones/ui.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../lib_chat/chat/index.dart';
import '../room_controller/room_controller.dart';
import '../room_controller/room_stateful_controller_mixin.dart';

class Debouncer {
  final Duration delay;
  Timer? _timer;

  Debouncer({required this.delay});

  void run(VoidCallback action) {
    _timer?.cancel();
    _timer = Timer(delay, action);
  }

  void dispose() {
    _timer?.cancel();
  }
}

class RoomInput extends StatefulWidget {
  const RoomInput({Key? key}) : super(key: key);

  @override
  _RoomInputState createState() => _RoomInputState();
}

class _RoomInputState extends State<RoomInput>
    with
        WidgetsBindingObserver,
        RoomStatefulControllerMixin<RoomController, RoomInput> {
  final FocusNode _focusNode = FocusNode();
  final TextEditingController _controller = TextEditingController();

  final Debouncer _debouncer =
      Debouncer(delay: const Duration(milliseconds: 250));
  double _lastStableHeight = 0.0;
  bool _isKeyboardVisible = false;

  double _currentKeyboardHeight = 0.0;
  double _maxKeyboardHeight = 0.0;
  bool _isShowEmoticon = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _loadMaxHeight(); // 初始化时加载保存的最高高度
  }

  @override
  void dispose() {
    _debouncer.dispose();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  /// 加载保存的最高高度
  Future<void> _loadMaxHeight() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _maxKeyboardHeight = prefs.getDouble('maxKeyboardHeight') ?? 0.0;
    });
  }

  /// 保存最高高度
  Future<void> _saveMaxHeight(double height) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setDouble('maxKeyboardHeight', height);
  }

  /// 隐藏键盘
  void _hideKeyboard() {
    _focusNode.unfocus();
  }

  /// 显示表情栏
  void _showEmoticon() {
    setState(() {
      _isShowEmoticon = true;
    });
    _hideKeyboard();
  }

  /// 隐藏输入框
  void _hideInputWidget() {
    _hideKeyboard();
    setState(() {
      _isShowEmoticon = false;
      _currentKeyboardHeight = 0;
    });
    roomController.isInputVisible.value = false;
  }

  @override
  void didChangeMetrics() {
    if (!mounted || !WidgetsBinding.instance.hasScheduledFrame) return;
    print("didChangeMetrics <<<<<<<<<<<<<<<<<<<<<<");
    final double newKeyboardHeight = MediaQuery.of(context).viewInsets.bottom;
    print("didChangeMetrics newKeyboardHeight: $newKeyboardHeight");
    // 防抖处理：延迟执行判断
    _debouncer.run(() {
      // 对比最终高度与上一次稳定高度
      if (_isKeyboardHeightStable(newKeyboardHeight, _lastStableHeight)) {
        _lastStableHeight = newKeyboardHeight;
        _updateKeyboardState(newKeyboardHeight);
      }
    });
    print(
        "didChangeMetrics _currentKeyboardHeight000: $_currentKeyboardHeight");
    if (newKeyboardHeight != _currentKeyboardHeight) {
      if (newKeyboardHeight < _currentKeyboardHeight &&
          newKeyboardHeight < _currentKeyboardHeight * 0.8 &&
          !_isShowEmoticon) {
        _hideInputWidget();

        print("didChangeMetrics _hideInputWidget: >>>");
      }
      setState(() {
        print(
            "didChangeMetrics _currentKeyboardHeight111: $_currentKeyboardHeight");
        if (!_isShowEmoticon && roomController.isInputVisible.value) {
          _currentKeyboardHeight = newKeyboardHeight;
          print(
              "didChangeMetrics _currentKeyboardHeight222: $_currentKeyboardHeight");
        }
        print(
            "didChangeMetrics _currentKeyboardHeight333: $_currentKeyboardHeight");
        if (newKeyboardHeight > 0 && newKeyboardHeight > _maxKeyboardHeight) {
          _maxKeyboardHeight = newKeyboardHeight;
          _saveMaxHeight(_maxKeyboardHeight); // 持久化保存
        }
      });
    }
    print("didChangeMetrics >>>>>>>>>>>>>>>>>>");
  }

  // 判断高度是否稳定（过滤平台手势栏干扰）
  bool _isKeyboardHeightStable(double currentHeight, double lastHeight) {
    const double threshold = 10.0; // 允许的误差范围
    return (currentHeight - lastHeight).abs() > threshold;
  }

  // 更新键盘状态
  void _updateKeyboardState(double height) {
    final bool newVisibility = height > _getMinKeyboardHeight();

    if (newVisibility != _isKeyboardVisible) {
      setState(() {
        _isKeyboardVisible = newVisibility;
        if (_isKeyboardVisible) {
          _isShowEmoticon = false;
          _currentKeyboardHeight = _maxKeyboardHeight;
        } else {
          _currentKeyboardHeight = 0;
        }
      });
      print("键盘最终状态: ${newVisibility ? '弹出 ($height)' : '收起'}");
    }
  }

  // 平台最小有效键盘高度（过滤系统手势栏）
  double _getMinKeyboardHeight() {
    switch (Theme.of(context).platform) {
      case TargetPlatform.android:
        return 150.0; // Android 手势栏通常 < 100px
      case TargetPlatform.iOS:
        return 250.0; // iOS 键盘最小高度
      default:
        return 100.0;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      if (!roomController.isInputVisible.value) {
        return Container();
      } else {
        return Column(
          children: [
            _buildOverlay(),
            _buildInputField(),
            _buildEmoticon(),
          ],
        );
      }
    });
  }

  Widget _buildOverlay() {
    return Expanded(
      child: GestureDetector(
        onTap: () => {_hideInputWidget()},
        child: Container(
          color: Color(0x4D000000),
        ),
      ),
    );
  }

  Widget _buildInputField() {
    return Container(
      color: Colors.white,
      height: 56.h,
      padding: EdgeInsets.symmetric(horizontal: 15.w),
      child: Row(
        children: [
          Expanded(
            child: Container(
              height: 30.h,
              decoration: BoxDecoration(
                color: const Color(0xFFF2F2F2),
                borderRadius: BorderRadius.circular(40.0.r),
              ),
              padding: EdgeInsetsDirectional.only(start: 13.w,end: 16.w),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: _controller,
                      focusNode: _focusNode,
                      autofocus: true,
                      decoration: const InputDecoration(
                        hintText: '输入消息...',
                        border: InputBorder.none,
                      ),
                      textInputAction: TextInputAction.send,
                      onEditingComplete: _hideInputWidget,
                      onSubmitted: (_) => _hideInputWidget,
                    ),
                  ),
                  SizedBox(
                    width: 6.w,
                  ),
                  Image.asset(
                    RoomAssets.roomEmoticonIcon,
                    width: 28.w,
                    height: 28.h,
                  ).onClick((){
                    _showEmoticon();
                  })
                ],
              ),
            ),
          ),
          SizedBox(
            width: 6.w,
          ),
          _sendButton(),
        ],
      ),
    );
  }

  Widget _sendButton() {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFF8A72FE),
        borderRadius: BorderRadius.circular(40.0.r),
      ),
      height: 30.h,
      padding: EdgeInsetsDirectional.only(start: 8.w, end: 12.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            RoomAssets.roomSendIcon,
            width: 28.w,
            height: 28.h,
          ),
          "Send".text(
            color: Colors.white,
            fontSize: 14.sp,
            weight: TextFontWeight.medium,
          )
        ],
      ).onClick(() {
        _hideInputWidget();
      }),
    );
  }

  Widget _buildEmoticon() {
    return Container(
        color: Colors.white,
        width: MediaQuery.of(context).size.width,
        height: _isShowEmoticon ? _maxKeyboardHeight : _currentKeyboardHeight,
        child: _isShowEmoticon
            ? MessageEmoji(
                onTap: (emoji) {
                  _controller.text += emoji;
                },
              )
            : Container());
  }
}
